#include "InetAddress.h"
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
#include <sstream>

using std::cout;
using std::endl;
using std::stringstream;

InetAddress::InetAddress(string ip, int port)
{
    ::memset(&addr_, 0, sizeof(addr_));
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port);
    addr_.sin_addr.s_addr = inet_addr(ip.c_str());
}

InetAddress::InetAddress(string ip, string port)
{
	::memset(&addr_, 0, sizeof(addr_));
    addr_.sin_family = AF_INET;
	//addr_.sin_port = htons(atoi(port.c_str()));
	addr_.sin_port = htons(str2int(port));
    addr_.sin_addr.s_addr = inet_addr(ip.c_str());
}

InetAddress::InetAddress(struct sockaddr_in &addr)
:addr_(addr)
{}

void InetAddress::printAddr() 
{
    cout << string(inet_ntoa(addr_.sin_addr)) << " " 
    << ntohs(addr_.sin_port) << endl;
}

string InetAddress::ip()
{
	return string(inet_ntoa(addr_.sin_addr));
}
int InetAddress::port()
{
	return ntohs(addr_.sin_port);
}

int InetAddress::str2int(string str)
{
	stringstream ss;
	ss << str;
	int tmp;
	ss >> tmp;
	return tmp;
}
